<!DOCTYPE html>
<html>
  <head>
    <title>无人探险地图编辑</title>
    <meta charset="utf-8">
  </head>
  <body>
	<script type="text/javascript" src="../libs/minicomps.min.js"></script>
	<script type="text/javascript" src="../libs/FileSaver.js"></script>
	<script type="text/javascript" src="../libs/easeljs.js"></script>
	<script type="text/javascript" src="../libs/helpWindow.js"></script>
	<script type="text/javascript" src="../libs/Unify.js"></script>
	<script>
	const { Toggle, HSlider,VSlider,Panel, Canvas ,Button,TextArea,TextBox,TextInput,Label,Window,LabelInput,TipsManager,RadioButton,ColorPicker,TabbarWindow,Checkbox,Knob,Stage,MoonTextArea,Dropdown,TabbarButton,ProgressBar} = mc
	const width = Stage.width;
	const height = Stage.height;
	const panel = new Panel(document.body, 0, 0, 10,10);
	var tip='事件：1墙,2敌人,3起始,4终点,5金币,6休息区域';
		tip+='\n参数：事件为敌人时 [排列样式(1:横,2:竖,3十字,4:横（左右对称）,5:竖（上下对称）,6:圆),数量,x轴间距,y轴间距]（向右向上是正值，向左向下是负值）';
		tip+='\n配置：事件为敌人时 [运行类型(1:直线运动,2:圆形运动,3:自转运动,4:方形运动),速度,x值,y值]---其它时候 [x轴数量,y轴数量]';
			
	var createStage;
	var group=1;
	var saveKey='noManGame'
	function updateColor(t){
		//console.log(t.toRGBString(),t.toString());
		if(currPanel&&currPanel.updateColor){
			currPanel.updateColor(t);
		}
	}
	var colors=['rgba(255,255,0,0.1)','#FF0000','#00bb00','#11dddd','#BB3300','#666600','#660000','#333399','#006666','#006633','#003300','#0033ff'];
			
	const helper=new HelpWindow(width,height);

	/**数字格式，把小于10的数在前面加个0*/
	function numberFormat(num){
		if(num>=10)			return String(num);
		else				return "0"+num;
	}
	/**复制行数*/
	function copyString(input){
		input.select();
		document.execCommand('Copy');
		TipsManager.alert('复制成功');
	}
	//基础面板
	class BasicPanel {
		constructor(label){
			this.isShow=true;
            this.p=new Canvas(document.body, 0, 0,width-10,height-15);
			this.p.setColorDark();
			new Label(this.p,5,-15,label).setBold(true).setFontSize(15);
		}
		set visible(value){//复盖父级方法
			if(this.isShow!=value){
				if(value) this.p.addFromParent();
				else	  this.p.removeFromParent();
			}
			this.isShow=value;
		}
		initData(){//子类去实现

		}
		setData(data){//子类去实现

		}
		setDataWindow(){
			this.dataWindow=new Window(this.p,0,0,window.innerWidth-150,window.innerHeight-100);
			this.dataWindow.visible=false;
			this.dataText=new MoonTextArea(this.dataWindow,0,22).setSize(this.dataWindow.width,this.dataWindow.height);
			this.dataWindow.btnClose=new Button(this.dataWindow,0,0,'复制关闭窗口',(e)=>{
				copyString(this.dataText.input);
				this.dataWindow.visible=false;
			});
			this.dataWindow.setContent=(str)=>{
				this.dataWindow.visible=true;
				this.dataText.text=str;
			}
		}
	}
	//-----------------地图编辑大师-----------------
	class MapToolPanel extends BasicPanel{
		constructor(label){
			super(label);
			this.propBtns=[];
			this.currSelMaps={};
			this.initView();
			this.initEvent();

			let data=localStorage.getItem(saveKey);
			if(data){
				this.createMap({detail:true,value:data});
			}else{
				this.createMap({detail:true});//测试
			}
			
		}
		initView(){
			this.canvas=new Canvas(this.p, 150, 0,width-160,height-15);
			this.realityCanvas=this.canvas.realityCanvas;
			var [x,y]=[5,-10];
			var [xNum,yNum,size]=[39,23,32];
			this.centerX=xNum*size/2;
			this.centerY=yNum*size/2;
			this.xTxt=new LabelInput(this.p,5,y+=22,'x轴数量').input;
			this.xTxt.setSize(50).text=xNum;
			this.yTxt=new LabelInput(this.p,5,y+=22,'y轴数量').input;
			this.yTxt.setSize(50).text=yNum;
			this.wMap=new LabelInput(this.p,5,y+=22,'小地图宽').input;
			this.wMap.setSize(50).text=size;
			new Button(this.p,x,y+=22,'创建地图',(e)=>{TipsManager.SureCancel(`确定创建${this.xTxt.text}x${this.yTxt.text}的地图吗？`,this.createMap.bind(this))});
			new Button(this.p,x,y+=22,'读取数据',(e)=>{TipsManager.SureCancel(`把数据输入到下方`,this.createMap.bind(this),true)});

			this.status=1;
			var [x,y,g,radios]=[5,110,++group,[]];
			this.inputs=[];
			let arr=['清除数据','使用数据1','使用数据2','使用数据3','使用数据4','使用数据5','使用数据6','使用数据7','使用数据8'];
			for(let i=0;i<arr.length;i++){
				radios.push(new RadioButton(this.p, x, (y+=22)+4, g, arr[i], i==1, (e)=>{
					for(let key in this.currSelMaps){
						let map=this.currSelMaps[key];
						map.setNewId({id:0,config:undefined,event:undefined});
					}
					this.stage.update();
					this.currSelMaps={};
					this.status=radios.indexOf(e.target);
				}));
				this.inputs.push(new TextInput(this.p,x+80,y,i,this.onInput.bind(this)).setSize(30));
			}

			this.toggleEdit=new Toggle(this.p, x+30, y+=40, '是否编辑',false,(e)=>{	this.isEdit=e.detail;	});
			new Button(this.p, x+6, y+=25, '生成JSON数据',(e)=>{	this.createJson();	});
			new Button(this.p, x+6, y+=25, '去试玩一下',(e)=>{window.location.href='gameMapEditer2-game.html';});

			this.setDataWindow();

			let smPanel=new Panel(this.p,0,height-60,width,60);
			(new TextArea(smPanel,0,0,tip)).setSize(width);
		}
		onInput(e){
			let i=this.inputs.indexOf(e.target);
			let text=e.detail;
			this.maps.forEach((a)=>{
				if(a.data.id==i){
					a.data.text=text;
					a.update();
				}
			})
			this.stage.update();
		}
		initEvent(){
			this.stage=new createjs.Stage(this.realityCanvas);
			this.stage.addEventListener("stagemousedown", this.handleMouseDown.bind(this));
			this.stage.addEventListener("stagemousemove", this.handleMouseMove.bind(this));
			this.stage.addEventListener("stagemouseup", this.handleMouseUp.bind(this));
			this.createBg('#ffffff');
			this.mapLayer=new createjs.Container();
			this.stage.addChild(this.mapLayer);
			createStage=this.stage;
			//setTimeout(()=>{this.stage.update},1000);//每秒刷新一次
		}
		handleMouseDown(event) {
			this.isDown=true;
			this.drawData={color:colors[this.status],text:this.inputs[this.status].text,id:this.status};
			const { x, y } = this.getPos(event);
			this.handleMouseMove(event);
			if(this.isEdit){
				if(this.isDown){
					const { x, y } = this.getPos(event);
					let len=this.maps.length;
					for(var i=0;i<len;i++){
						let a=this.maps[i];
						if(a.data.id>0&&a.hitTest(x, y)){
							if(this.dataEditWindow==null){
								this.dataEditWindow=new DataEditWindow(document.body,0,0);
							}else{
								this.dataEditWindow.addFromParent();
							}
							this.dataEditWindow.setData(a);
							return;
						}
					}
					TipsManager.alert('请关闭编辑');
				}
			}
		}
		handleMouseMove(event) {
			if(this.isEdit)return;
			if(this.isDown){
				const { x, y } = this.getPos(event);
				let len=this.maps.length;
				for(var i=0;i<len;i++){
					let a=this.maps[i];
					//if(a.data.event)
					if(a.hitTest(x, y)){
						a.setData(this.drawData);
						this.stage.update();
						this.currSelMaps[a.pos]=a;
						break;
					}
				}
			}
		}
		handleMouseUp(event) {
			//console.log(this.currSelMaps);
			let data=this.currSelMaps;
			let [maxX,maxY,minX,minY]=[0,0,999,999];
			let cnt=0;
			for(let key in data){
				let [x,y]=key.split(',').map(a=>Number(a));
				maxX=Math.max(maxX,x);
				maxY=Math.max(maxY,y);
				minX=Math.min(minX,x);
				minY=Math.min(minY,y);
				cnt++;
			}
			//console.log(maxX,maxY,minX,minY);
			let [numX,numY]=[maxX-minX+1,maxY-minY+1];
			if((numX!=1||numY!=1)&&(numX-1)%2==0&&(numY-1)%2==0&&numX*numY==cnt){
				let [cenX,cenY]=[Math.floor(numX/2)+minX,Math.floor(numY/2)+minY];
				//console.log(cenX,cenY);
				let map=this.mapDatas[cenY][cenX];
				let [x,y]=[map.x-this.centerX,this.centerY-map.y];
				let config=numX+','+numY;
				let pos=x+','+y;
				let event=map.data.id;
				map.setNewId({id:8,config:config,event:event,pos:pos});
				this.currSelMaps={};
			}
			if(numX==1&&numY<=2||numX<=2&&numY==1){
				let { x, y } = this.getPos(event);
				let len=this.maps.length;
				for(var i=0;i<len;i++){
					let a=this.maps[i];
					if(a.hitTest(x, y)){
						let [x,y]=[a.x-this.centerX,this.centerY-a.y];
						let pos=x+','+y;
						let event=a.data.id;
						if(a.data.id==1){
							let config=numX+','+numY;
							a.setNewId({id:8,config:config,event:event,pos:pos});
						}else{
							a.setNewId({id:a.data.id,pos:pos,event:event});
						}						
						break;
					}
				}
				this.currSelMaps={};
			}

			this.isDown=false;
			this.stage.update();
		}
		getPos(evt) {
			return {
				x: evt.stageX,
				y: evt.stageY
			}
		}
		createMap(e){
			if(e.detail){
				this.mapLayer.removeAllChildren();
				if(e.value){
					try{
						var json=JSON.parse(e.value);
						var [ x, y ,w] = json.size.split(',').map(a=>Number(a));
						//w=32;
					}catch (error) {
						TipsManager.alert('JSON数据错误');
						console.error('JSON数据错误');
						return;
					}
				}else{
					var [ x, y ,w] = [Number(this.xTxt.text),Number(this.yTxt.text),Number(this.wMap.text)];
				}
				this.maps=[];
				this.mapDatas=[];
				for(let i=0;i<y;i++){
					this.mapDatas.push([]);
					for(let j=0;j<x;j++){
						let map=new MapItem(w,w);
						map.pos=[j,i];
						this.mapLayer.addChild(map);
						this.maps.push(map);
						this.mapDatas[i].push(map);
					}
				}
				Unify.displayRank(this.maps,x);
				this.minMapWid=w;
				if(json){
					for(var key in json){
						let da=json[key];
						if(key=='size') continue;
						let [x,y]=key.split(',').map(a=>Number(a));
						let map=this.mapDatas[y][x];
						let id=da.id;
						da['text']=id;
						da['color']=colors[id];
						map.setData(da);
						if(da.event==1||da.event==3||da.event==4){
							let id=da.event;
							let [numX,numY]=[0,0]
							if(da.config)[numX,numY]=da.config.split(',').map(a=>(Math.floor(a/2)));
							let [minX,maxX,minY,maxY]=[x-numX,x+numX,y-numY,y+numY];
							for(let i=minX;i<=maxX;i++){
								for(let j=minY;j<=maxY;j++){
									let mp=this.mapDatas[j][i];
									if(mp!=map){
										let da={'id':id,'text':id,'color':colors[id]};
										mp.setData(da);
									}
								}
							}
						}
					}
					this.toggleEdit.setEnabled(true);
				}
				this.redPoint.x=x*w/2;
				this.redPoint.y=y*w/2;
				this.stage.update();
			}
		}
		createJson(){
			var value="{"+'"'+"size"+'":"'+this.mapDatas[0].length+','+this.mapDatas.length+',32",'
			this.maps.forEach((item)=>{
				if(item.data.id){
					if(item.data.event){
						var o={id:item.data.id,pos:item.data.pos,event:item.data.event};
						if(item.data.param)o.param=item.data.param;
						if(item.data.config)o.config=item.data.config;
						var v='"'+item.pos.toString()+'":'+JSON.stringify(o)+',';
						value+=v;
					}
				}
			});
			value=value.substr(0,value.length-1);
			value+="}";
			localStorage.setItem(saveKey,value);
			this.dataWindow.setContent(value);
		}
		createBg(color){
			if(!this.bg){
				this.bg=new createjs.Shape();
				this.bg.graphics.beginFill(color).drawRect(0,0,this.canvas.width,this.canvas.height);
				this.stage.addChildAt(this.bg,0);
			}else{
				this.bg.graphics.clear().beginFill(color).drawRect(0,0,this.canvas.width,this.canvas.height);
			}
			let center=new createjs.Shape();
			center.graphics.beginFill('#ff0000').drawCircle(0,0,5);
			[center.x=this.centerX,center.y=this.centerY];
			this.stage.addChild(center);
			this.stage.update();
			this.redPoint=center;//红点
		}
	}
	class DataEditWindow extends Window{
		constructor(parent, xpos, ypos)
		{
			super(parent, xpos, ypos);
			let w=150;
			this.setSize(w,w+100);
			this.x=0;
			this.y=430;
			this.createText();
			
			this.draggable=false;
			let [x,y]=[5,120];
		}
		createText(){
			var names=['id','事件','参数','配置','位置','',''];
			var h=30;
			var win=this;
			for(var i=0;i<names.length;i++){
				new Label(this,0,i*h,names[i]);
				switch(i){
					case 0:
						this.txtId=new TextInput(win,50,i*h,);
						this.txtId.setSize(100,26);
						break;
					case 1:
						this.txtEvent=new TextInput(win,50,i*h);
						this.txtEvent.setSize(100,26);
						break;
					case 2:
						this.txtParam=new TextInput(win,50,i*h);
						this.txtParam.setSize(100,26);
						break;
					case 3:
						this.txtConfig=new TextInput(win,50,i*h);
						this.txtConfig.setSize(100,26);
						break;
					case 4:
						this.txtPos=new TextInput(win,50,i*h);
						this.txtPos.setSize(100,26);
						break;	
					case 5:
						new Button(win,50,i*h,'确定修改',this.onSure.bind(this));
						break;
					case 6:
						new Button(win,50,i*h,'配置说明',this.onAlert.bind(this));
						break;
						
				}
			}
		}
		onAlert(){
			alert(tip);
		}
		setData(item){
			this.item=item;
			this.txtId.text=this.item.data.id;
			this.txtEvent.text=this.item.data.event||'';
			this.txtParam.text=this.item.data.param||'';
			this.txtConfig.text=this.item.data.config||'';
			this.txtPos.text=this.item.data.pos||'';
		}
		onSure(){
			this.item.data.id=this.txtId.text||0;
			this.item.data.text=this.txtId.text||'';
			this.item.data.color=colors[this.item.data.id];
			this.item.data.event=this.txtEvent.text||'';
			this.item.data.param=this.txtParam.text||'';
			this.item.data.config=this.txtConfig.text||'';
			this.item.data.pos=this.txtPos.text||'';
			this.item.update();
			createStage.update();
		}
		removeFromParent(){
			this.onSure();
			super.removeFromParent();
		}
	}
	customElements.define("minimal-window99", DataEditWindow);
	class MapItem extends createjs.Container{
		constructor(w,h){
			super();
			this.data={id:0};
			this.width=w;
			this.height=h;
			this.shape=new createjs.Shape();
			this.colorBg="rgba(255,255,0,0.1)";
			this.colorMap="rgba(255,0,0,1)";
			this.drawBox(this.colorBg);
			this.addChild(this.shape);
			this.label=new createjs.Text('',"15px Arial", "#ffffff");
			this.label.x=3;
			this.label.y=3;
			this.label.textAlign='left';
			this.addChild(this.label);
		}
		drawBox(color){
			let[w,h]=[this.width,this.height];
			this.shape.graphics.clear();
			this.shape.graphics.setStrokeStyle(1);
			this.shape.graphics.beginStroke("black");
			this.shape.graphics.beginFill(color).drawRect(0,0,w,h);
		}
		hitTest(x,y){
			if(x>=this.x&&x<=this.x+this.width){
				if(y>=this.y&&y<=this.y+this.height){
					return true;
				}
			}
			return false;
		}
		setData(data){
			this.data.id=data.id;
			this.data.text=data.text;
			this.data.color=data.color;
			this.data.event=data.event;
			this.data.param=data.param;
			this.data.config=data.config;
			this.data.pos=data.pos;
			this.update();
		}
		setNewId(data){
			this.data.id=data.id;
			this.data.text=data.id;
			this.data.color=colors[data.id];
			this.data.event=data.event;
			this.data.config=data.config;
			this.data.pos=data.pos;
			this.update();
		}
		update(){
			this.label.text=this.data.text||'';
			this.drawBox(this.data.color);
			//console.log(this.label.text,this.data.color);
		}
	}
	//--所有面板----
	var btnNames=['地图编辑'];
	var buttons=[];
	var currPanelIndex=0;
	var currPanel=null;
	for(var i=0;i<btnNames.length;i++){
		var btn=new Button(panel,2,2+22*i,btnNames[i],onClick);
		buttons.push(btn);
		btn.setSize(88);
		btn.name=i;
	}
	
	function onClick(e){
		let btn=e.target;
		changeView(btn);
	}
	function changeView(btn){
		let name=btn.name;
		buttons.forEach((b)=>{b.enabled=true;});
		btn.enabled=false;
		for(var i=0;i<panels.length;i++){
			panels[i].visible=false;
		}
		currPanel=panels[name]
		currPanel.visible=true;
		currPanel.initData();
		currPanelIndex=name;
		
	}
	var panelClass=[
		[MapToolPanel,'地图编辑大师']
	];
	var panels=[];
	for(var i=0;i<panelClass.length;i++){
		let panel=new panelClass[i][0](panelClass[i][1]);
		panel.visible=false;
		panels.push(panel);
	}
	changeView(buttons[0]);
	</script>
  </body>
</html>